<template>
  <div class="cs-page-container">
    <div class="cs-filter-container">
      <el-select
        v-model="historyQuery.interval"
        clearable
        filterable
        placeholder="周期"
        style="width:100px"
      >
        <el-option label="1分钟" value="1" />
        <el-option label="5分钟" value="5" />
        <el-option label="10分钟" value="10" />
        <el-option label="30分钟" value="30" />
        <el-option label="60分钟" value="60" />
      </el-select>
      <el-date-picker
        v-model="historyDaterangeValue"
        :picker-options="daterangePickerOptions"
        type="datetimerange"
        align="right"
        unlink-panels
        range-separator="至"
        start-placeholder="创建起始时间"
        end-placeholder="创建结束时间"
        value-format="yyyy/MM/dd HH:mm:ss"
        format="yyyy/MM/dd HH:mm:ss"
        :default-time="['00:00:00', '00:00:00']"
        @change="MydaterangeChanged"
      />
      <el-button
        type="primary"
        size="small"
        icon="el-icon-search"
        @click="handleFilter"
      >搜索</el-button>
      <el-button
        type="info"
        size="small"
        icon="el-icon-refresh-right"
        @click="resetFilter"
      >重置</el-button>
    </div>
    <LineChart :options="chartOptions" style="width:1500%;height:400px" />
    <div class="cs-filter-container">
      <el-input
        v-model.trim="listQuery.userId"
        clearable
        placeholder="请输入用户ID"
      />
      <el-input
        v-model="listQuery.nickname"
        clearable
        placeholder="用户昵称"
        style="width:130px"
      />
      <el-select
        v-model="listQuery.gender"
        clearable
        filterable
        placeholder="性别"
        style="width:100px"
      >
        <el-option label="未知" value="0" />
        <el-option label="男" value="1" />
        <el-option label="女" value="2" />
      </el-select>
      <el-select
        v-model="listQuery.identifyType"
        filterable
        placeholder="认证类型"
      >
        <el-option label="未认证" :value="0" />
        <el-option label="真人认证" :value="1" />
        <el-option label="女神认证" :value="2" />
      </el-select>
      <el-select
        v-model="listQuery.channel"
        clearable
        filterable
        placeholder="渠道"
      >
        <el-option
          v-for="(channel, i) in channels"
          :key="i"
          :label="channel"
          :value="channel"
        />
      </el-select>
      <el-date-picker
        v-model="daterangeValue"
        :picker-options="daterangePickerOptions"
        type="daterange"
        align="right"
        unlink-panels
        range-separator="至"
        start-placeholder="创建起始时间"
        end-placeholder="创建结束时间"
        value-format="yyyy/MM/dd"
        @change="daterangeChanged"
      />
      <el-button
        type="primary"
        size="small"
        icon="el-icon-search"
        @click="handleFilter"
      >搜索</el-button>
      <el-button
        type="info"
        size="small"
        icon="el-icon-refresh-right"
        @click="resetFilter"
      >重置</el-button>
    </div>
    <div class="cs-filter-result">
      <el-table
        id="anchorListFirst"
        v-loading="listLoading"
        :data="list"
        :height="'calc(100vh - 330px)'"
        border
        fit
        size="small"
        highlight-current-row
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
      >
        <el-table-column align="center" label="用户ID">
          <template slot-scope="{ row }">
            <TooptipsCom :user-id="row.accountId" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="昵称" prop="nickname" />
        <el-table-column align="center" label="性别">
          <template slot-scope="{ row }">{{ row.gender | gender }}</template>
        </el-table-column>
        <el-table-column align="center" label="激活渠道" prop="appChannel" />
        <el-table-column align="center" label="真人/女神认证">
          <template slot-scope="{ row }">{{ identifyTypeItems[row.certification] }}</template>
        </el-table-column>
        <el-table-column align="center" label="最后登录时间" prop="onlineTime">
          <template slot-scope="{row}">{{ row.onlineTime | parseTime }}</template>
        </el-table-column>
        <el-table-column align="center" label="魅力等级/魅力值" prop="charm" />
        <el-table-column align="center" label="土豪等级/土豪值" prop="localTyrants" />
        <el-table-column align="center" label="当天打招呼次数" prop="greet" />
        <el-table-column align="center" label="匹配权重（女）" prop="weight" />
        <el-table-column align="center" label="当天搭讪次数" prop="accost" />
        <el-table-column align="center" label="操作" width="160">
          <template slot-scope="{ row }">
            <el-button type="primary" size="mini" @click="onGoDetail(row.accountId.toString())">
              详情
            </el-button>
            <el-button
              type="danger"
              size="mini"
              @click="onForbid(row)"
            >
              封号
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <TablePagination
        :current-page="listQuery.page"
        :limit="listQuery.limit"
        :total="total"
        :loading="listLoading"
        @handleSizeChange="handleSizeChange"
        @handleCurrentChange="handleCurrentChange"
      />
      <el-dialog
        v-loading="dialogLoading"
        title="聊天详情"
        :visible.sync="dialogVisible"
        width="50%"
      >
        <div v-if="chatDetail" class="detail-box">
          <div v-for="(item, index) in chatDetail" :key="index" class="list-item" style="width: 70%;">
            <div class="item-name">
              <div v-if="item.fromGender === 1" class="comment_item" style="display: inline-block; left: 50px;">
                <el-avatar :size="40" :src="item.content" style="display: inline-block; left: 20px; position: absolute;">
                  <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" alt="" />
                </el-avatar>
                <div class="comment_content" style="display: inline-block; left: 70px; width: 75%;">
                  <span style="display: block; padding-bottom: 6px;">{{ item.fromUser }}</span>
                  <span v-if="item.replayUserNickname">回复 {{ item.replayUserNickname }}</span>
                  <span>{{ item.content }}</span>
                  <span>{{ item.sendTime | formatTime }}</span>
                </div>
              </div>

              <div v-if="item.fromGender === 2 || item.fromGender === 0" class="comment_item">
                <div class="comment_content" style="display: inline-block; right: 70px; width: 75%; text-align: right;">
                  <span style="display: block; padding-bottom: 6px; text-align: right;">{{ item.fromUser }}</span>
                  <span>{{ item.content }}</span>
                  <span>{{ item.sendTime | formatTime }}</span>
                </div>
                <el-avatar :size="40" :src="item.content" style="display: inline-block; right: 20px; position: absolute;">
                  <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" alt="" />
                </el-avatar>
              </div>
            </div>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="dialogVisible = false"
          >确 定</el-button>
        </span>
      </el-dialog>
      <DialogForbidAccount
        :visible.sync="sealNumberVisible"
        :user-ids="forbidAccounts"
        :forbid-type="'0'"
        @onSuccess="doSearch"
      />
    </div>
  </div>
</template>

<script>
// eslint-disable-next-line no-unused-vars
import TablePagination from '@/components/TablePagination'
import DATEPICKER_OPTIONS from '@/config/datepickerOptions';
import LineChart from '@/components/LineChart'
import { xhrAnalysisOnlineUser, xhrAnalysisOnlineHistory } from '@/api/account'
import DialogForbidAccount from '@/views/account/components/DialogForbidAccount'
import { deepClone } from '@/utils';
export default {
  name: 'OnlineUser',
  components: { TablePagination, DialogForbidAccount, LineChart },
  data() {
    return {
      list: null,
      historylist: null,
      total: 0,
      channels: [],
      chartOptions: {},
      daterangeValue: '',
      historyDaterangeValue: '',
      dialogLoading: true,
      dialogVisible: false,
      sealNumberVisible: false,
      forbidAccounts: '',
      identifyTypeItems: { 0: '未认证', 1: '真人', 2: '主播' },
      chatDetail: null,
      daterangePickerOptions: DATEPICKER_OPTIONS.daterangePickerOptions,
      listQuery: {
        page: 1,
        limit: 100,
        startTime: null,
        endTime: null,
        identifyType: null,
        channel: null,
        nickname: null,
        gender: null,
        userId: (this.$route.query && this.$route.query.id) || null
      },
      historyQuery: {
        startTime: null,
        endTime: null,
        interval: null
      }
    }
  },
  created() {
    this.doSearch()
    this.getChannels()
  },
  methods: {
    getChannels() {
      this.xhrGetChannels().then(resp => {
        this.channels = resp.data
      })
    },
    doSearch: function() {
      xhrAnalysisOnlineUser(this.listQuery)
          .then(resp => {
            this.list = resp.data.list
            this.total = resp.data.count
            this.listLoading = false
          })
          .catch(err => {
            this.$message.error(err)
            this.listLoading = false
          })
      const historyQuery = deepClone(this.historyQuery)
      if (!historyQuery.interval) {
        historyQuery.interval = 5
      }
      const interval = (60 * 1000) * historyQuery.interval
      if (!historyQuery.endTime) {
        historyQuery.endTime = parseInt(new Date().getTime())
      }
      if (!historyQuery.startTime) {
        historyQuery.startTime = historyQuery.endTime - (1000 * 60 * 60 * 24);
      }
      xhrAnalysisOnlineHistory(historyQuery)
          .then(resp => {
            const historyData = {}
            for (const i in resp.data.list) {
              const rowData = historyData[new Date(resp.data.list[i].dateTime).getTime()] ? historyData[new Date(resp.data.list[i].dateTime).getTime()] : {}
              if (resp.data.list[i].onlineStatus === 1) {
                rowData.frontOnline = rowData.frontOnline ? rowData.frontOnline + resp.data.list[i].onlineCount : resp.data.list[i].onlineCount
              } else {
                rowData.backstageOnline = rowData.backstageOnline ? rowData.backstageOnline + resp.data.list[i].onlineCount : resp.data.list[i].onlineCount
              }
              historyData[new Date(resp.data.list[i].dateTime).getTime()] = rowData
            }
            historyQuery.startTime = historyQuery.startTime - (historyQuery.startTime % interval);
            const series = [
              {
                name: 'app前台在线',
                type: 'line',
                data: []
              },
              {
                name: 'app后台在线',
                type: 'line',
                data: []
              },
              {
                name: '总在线',
                type: 'line',
                data: []
              }
            ]
            const inventoryDate = []
            while (historyQuery.startTime < historyQuery.endTime) {
              const tmp = historyData.hasOwnProperty(historyQuery.startTime) ? historyData[historyQuery.startTime] : {
                frontOnline: 0,
                backstageOnline: 0
              }
              if (!tmp.frontOnline) {
                tmp['frontOnline'] = 0
              }
              if (!tmp.backstageOnline) {
                tmp['backstageOnline'] = 0
              }
              series[0].data.push(tmp.frontOnline)
              series[1].data.push(tmp.backstageOnline)
              series[2].data.push(tmp.frontOnline + tmp.backstageOnline)
              const time = new Date(historyQuery.startTime);
              const y = time.getFullYear();
              const m = time.getMonth() + 1;
              const d = time.getDate();
              const h = time.getHours();
              const mm = time.getMinutes();
              const s = time.getSeconds();
              inventoryDate.push(y + '-' + this.add0(m) + '-' + this.add0(d) + ' ' + this.add0(h) + ':' + this.add0(mm) + ':' + this.add0(s))
              historyQuery.startTime += interval
            }
            this.drawLine(inventoryDate, series)
            console.log(this.chartOptions)
          })
          .catch(err => {
            this.$message.error(err)
          })
    },
    add0(m) { return m < 10 ? '0' + m : m },
    dataRefreh() {
      this.listLoading = true
      this.doSearch()
      this.$forceUpdate();
    },
    onGoDetail(id) {
      this.$router.push('/account/account-detail?id=' + id)
    },
    onForbid(row) {
      this.forbidAccounts = row.accountId.toString()
      this.sealNumberVisible = true
    },
    drawLine(inventoryDate, series) {
      this.chartOptions = {
        title: {
          text: '历史在线'
        },
        legend: {
          data: ['app前台在线', 'app后台在线', '总在线']
        },
        xAxisData: inventoryDate,
        series: series
      }
      this.this.$forceUpdate();
    },
    MydaterangeChanged() {
      if (this.historyDaterangeValue) {
        if (this.historyDaterangeValue[0]) {
          const startTime = this.historyDaterangeValue[0]
          this.historyQuery.startTime = /\d{2}:\d{2}$/g.test(startTime)
              ? new Date(startTime).getTime()
              : new Date(startTime + ' 00:00:00').getTime()
        }
        if (this.historyDaterangeValue[1]) {
          const endTime = this.historyDaterangeValue[1]
          this.historyQuery.endTime = /\d{2}:\d{2}$/g.test(endTime)
              ? new Date(endTime).getTime()
              : new Date(endTime + ' 23:59:59').getTime()
        }
      } else {
        this.historyQuery.startTime = null
        this.historyQuery.endTime = null
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.comment_content{
  position: absolute;
}
.children-item{
  margin-left: 20px;
}
.item-name{
  height: 70px;
}
.comment_item{
}
.el-dialog{
  overflow: auto;
}
</style>
